package com.anysoft.me.base;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.anysoft.MentorApplication;
import com.anysoft.R;
import com.anysoft.WebViewNetworkProtocol;
import com.anysoft.base.BaseActivity;
import com.anysoft.bean.JsBean;
import com.anysoft.me.config.ServiceConfig;
import com.anysoft.utils.ActivityUtils;
import com.anysoft.utils.AnalyticsEventUtils;
import com.anysoft.utils.ChinaPayUtils;
import com.anysoft.utils.MentorLogger;
import com.anysoft.utils.StatusBarUtils;
import com.anysoft.utils.StringUtils;
import com.anysoft.view.CustomMarqueeTextView;
import com.anysoft.view.HProgressBarLoading;
import com.google.gson.Gson;
import com.hxcr.chinapay.activity.Initialize;
import com.hxcr.chinapay.util.CPGlobaInfo;
import com.hxcr.chinapay.util.Utils;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import ren.yale.android.cachewebviewlib.CacheWebView;
import ren.yale.android.cachewebviewlib.WebViewCache;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static com.anysoft.HostConstant.HOST_WEB_URL_HEADER;

/**
 * Created by lty on 2017/12/27.
 */

public abstract class BaseFundWebViewActivity extends BaseActivity {

    public final String TAG = this.getClass().getSimpleName() + "===>";
    @BindView(R.id.leftButton)
    public Button leftButton;
    @BindView(R.id.rightButton)
    public ImageView rightButton;
    @BindView(R.id.cmtv_title)
    public CustomMarqueeTextView cmtv_title;
    @BindView(R.id.sub_title)
    public TextView subTitle;
    @BindView(R.id.shareButton)
    public ImageView shareButton;

    @BindView(R.id.wv)
    public CacheWebView mWebView;

    @BindView(R.id.tv_item_web_error)
    public TextView tvItemWebError;
    @BindView(R.id.ll_item_web_error)
    public LinearLayout llItemWebError;
    @BindView(R.id.top_progress)
    public HProgressBarLoading top_progress;

    public String loadUrl;
    private boolean isLoadError;
    public Intent mIntent = new Intent();
    public boolean isCanPressBack = true;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        doBeforeSetContentView();
        setContentView(R.layout.activity_webview_fund_detail_layout);
        ButterKnife.bind(this);
        setShowErrorView(false);
        mWebView.setCacheStrategy(WebViewCache.CacheStrategy.FORCE);
        CacheWebView.servicePreload(this, loadUrl);//通过启动Service来预加载，不影响UI线程
        tvItemWebError.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mWebView.setVisibility(View.GONE);
                llItemWebError.setVisibility(View.GONE);
                reLoadPage(loadUrl);
            }
        });
    }

    @Override
    protected void onResume() {
        if (mWebView != null) {
            mWebView.onResume();
        }
        super.onResume();
    }

    @Override
    protected void onPause() {
        if (mWebView != null) {
            mWebView.onPause();
        }
        super.onPause();
    }

    /**
     * 在布局之前做的一些操作
     */
    protected void doBeforeSetContentView() {
        setStatusBarColor(R.color.fund_title);
    }

    public abstract void onshouldOverrideUrlLoadingCallBack(WebView webview, String url);


    public void setWebViewConfig(String url) {
        if (mWebView == null || StringUtils.isNullOrEmpty(url)) {
            MentorLogger.Loge("url不能为空 或者 webview不能为空");
            return;
        }
        // TODO: 2018/1/19 防止通过file域来恶意攻击
        mWebView.getSettings().setAllowFileAccess(false);
        if (loadUrl.startsWith("file://")) {
            mWebView.getSettings().setJavaScriptEnabled(false);
            mWebView.getSettings().setAllowFileAccessFromFileURLs(false);
            mWebView.getSettings().setAllowUniversalAccessFromFileURLs(false);
        } else {
            mWebView.getSettings().setJavaScriptEnabled(true);
        }
        mWebView.setWebViewClient(mWebViewClient);
        mWebView.setWebChromeClient(mWebChromeClient);
        //设置本地调用对象及其接口
        mWebView.addJavascriptInterface(new JavaScriptObject(), "js_invoke");
        if (url.startsWith("http")) {
            mWebView.loadUrl(url);
        } else {
            mWebView.loadDataWithBaseURL("about:blank", url, "text/html", "utf-8", null);
        }
        mWebView.removeJavascriptInterface("searchBoxJavaBridge_");
        mWebView.removeJavascriptInterface("accessibility");
        mWebView.removeJavascriptInterface("accessibiltyTraversal");
    }


    private WebViewClient mWebViewClient = new WebViewClient() {

        @Override
        public void onLoadResource(WebView view, String url) {
            MentorLogger.Loge(TAG, "onLoadResource " + view.getProgress());
            super.onLoadResource(view, url);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView webview, String url) {
            MentorLogger.Loge(TAG, "shouldOverrideUrlLoading url=" + url);
            if (url.contains(WebViewNetworkProtocol.GO_IDCARD_UPLOAD_SPECIAL)) {
                ActivityUtils.gotoUploadIditityCardActivity(BaseFundWebViewActivity.this, "0", "6");
                return true;
            }
            onshouldOverrideUrlLoadingCallBack(webview, url);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            MentorLogger.Log(TAG, "onPageStarted " + view.getProgress());
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            String title = view.getTitle();
            MentorLogger.Loge(TAG, "onPageFinished WebView title=" + title);
            if (!isLoadError) {
                setShowErrorView(false);
            } else {
                isLoadError = false;
                setShowErrorView(true);
            }

            if ("网页无法打开".equals(title) || title.contains("404")) {
                setShowErrorView(true);
            }
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            MentorLogger.Loge(TAG, "onReceivedError" + error.getErrorCode());
            isLoadError = true;
            setShowErrorView(true);
            super.onReceivedError(view, request, error);
        }

        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            MentorLogger.Loge(TAG, "onReceivedHttpError" + errorResponse.getStatusCode());
            super.onReceivedHttpError(view, request, errorResponse);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();// 接受所有网站的证书  前两个是代表日期问题，第三个是webview的bug，最后一个是证书丢失，
//            if (error.getPrimaryError() == SslError.SSL_DATE_INVALID
//                    || error.getPrimaryError() == SslError.SSL_EXPIRED
//                    || error.getPrimaryError() == SslError.SSL_INVALID
//                    || error.getPrimaryError() == SslError.SSL_UNTRUSTED) {
//
//                handler.proceed();
//
//            } else {
//                handler.cancel();
//            }
            MentorLogger.Loge(TAG, "onReceivedSslError" + error.getUrl());
        }
    };


    private WebChromeClient mWebChromeClient = new WebChromeClient() {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            MentorLogger.Loge(TAG, "onProgressChanged:" + newProgress);
            top_progress.setCurProgress(newProgress);
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            MentorLogger.Loge(TAG, "onJsAlert:" + message);
            result.confirm();
            return true;
        }

        @Override
        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
            MentorLogger.Loge(TAG, "onJsConfirm:" + message);
            return super.onJsConfirm(view, url, message, result);
        }

        @Override
        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
            MentorLogger.Loge(TAG, "onJsPrompt:" + url);
            return super.onJsPrompt(view, url, message, defaultValue, result);
        }
    };


    public void goBackOrFinish() {
        if (mWebView != null) {
            mWebView.evaluateJavascript("goBackFundFile()", new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String s) {
                    if ("\"1\"".equals(s)) {
                        finish();
                    }
                }
            });
        } else {
            finish();
        }
    }

    public void setStatusBarColor(int resId) {
        StatusBarUtils.setWindowStatusBarColor(this, resId);
    }

    public String generateUrl(String action, String param) {
        loadUrl = HOST_WEB_URL_HEADER + action + ".html?isFromApp=true&" + param;
        MentorLogger.Log(TAG, "loadUrl=" + loadUrl);
        return loadUrl;
    }

    public void reLoadPage(String url) {
        setWebViewConfig(url);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    public static HashMap<String, String> handleUrlParams(String url) {
        HashMap<String, String> hm = new HashMap<String, String>();
        if (url.contains("?") && url.indexOf("?") != url.length() - 1) {
            String params = url.substring(url.indexOf("?") + 1);
            if (params.contains("&")) {
                String[] paramArr = params.split("&");
                for (int i = 0; i < paramArr.length; i++) {
                    String str = paramArr[i];
                    if (str.contains("=")) {
                        hm.put(str.substring(0, str.indexOf("=")),
                                str.substring(str.indexOf("=") + 1,
                                        str.length()));
                    }
                }
            } else {
                if (params.contains("=")) {
                    hm.put(params.substring(0, params.indexOf("=")),
                            params.substring(params.indexOf("=") + 1,
                                    params.length()));
                }
            }
        }
        return hm;
    }

    @Override
    protected void onDestroy() {
        if (mWebView != null) {
            //加载空内容
            mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            mWebView.removeAllViews();
            ((ViewGroup) mWebView.getParent()).removeView(mWebView);
            mWebView.destroy();
            mWebView = null;
        }
        super.onDestroy();
    }

    class JavaScriptObject {
        @JavascriptInterface
        public void gotoChinaPay(String json) {
            //System.out.println("json---" + json);
            UpdateChinaPayAuth(json);
        }


        @JavascriptInterface
        public void t_buy_apply_bank() {
            AnalyticsEventUtils.toBuyApplyBankEvent(MentorApplication.context);
        }

        @JavascriptInterface
        public void t_buy_apply_482002() {
            AnalyticsEventUtils.toBuyApply_XJKXEvent(MentorApplication.context);
        }

        @JavascriptInterface
        public void t_buy_confirm() {
            AnalyticsEventUtils.toBuyConfirmEvent(MentorApplication.context);
        }

        @JavascriptInterface
        public void t_buy_result() {
            AnalyticsEventUtils.toBuyResultEvent(MentorApplication.context);
        }

        @JavascriptInterface
        public void t_redeem_apply_bank() {
            AnalyticsEventUtils.toRedeemApplyBankEvent(MentorApplication.context);
        }

        @JavascriptInterface
        public void t_redeem_apply_482002() {
            AnalyticsEventUtils.toRedeemApplay_XJKXEvent(MentorApplication.context);
        }

        @JavascriptInterface
        public void t_redeem_confirm() {
            AnalyticsEventUtils.toRedeemConfirmEvent(MentorApplication.context);
        }

        @JavascriptInterface
        public void t_redeem_result() {
            AnalyticsEventUtils.toRedeemResultEvent(MentorApplication.context);
        }

        @JavascriptInterface
        public void t_transfer_apply() {
            AnalyticsEventUtils.toTransferApplayEvent(MentorApplication.context);
        }

        @JavascriptInterface
        public void t_transfer_confirm() {
            AnalyticsEventUtils.toTransferConfirmEvent(MentorApplication.context);
        }

        @JavascriptInterface
        public void t_transfer_result() {
            AnalyticsEventUtils.toTransferResultEvent(MentorApplication.context);
        }

        @JavascriptInterface
        public void openBack() {
            isCanPressBack = true;
        }

        @JavascriptInterface
        public void closeBack() {
            isCanPressBack = false;
        }
    }

    /**
     * 银联插件报文获取
     */
    private void UpdateChinaPayAuth(String json) {
        JsBean bean;
        try {
            bean = new Gson().fromJson(json, JsBean.class);
        } catch (Exception exception) {
            showConfirmAlert(mActivity, "提示", "数据解析错误");
            return;
        }

        if (bean == null) {
            showConfirmAlert(mActivity, "提示", getString(R.string.no_data));
            return;
        }

        Utils.setPackageName(getPackageName());
        String xml = ChinaPayUtils.getXml(ServiceConfig.CHINA_PAY_ENVIRONMENT, bean.getMerId(), bean.getMerOrderId(),
                bean.getMerOrderTime(), bean.getCharactercode(), bean.getSign());

        // 调用银行插件进行开户，在此类的onResume()方法中获取插件的返回结果
        Intent inten = new Intent(this, Initialize.class);
        inten.putExtra(CPGlobaInfo.XML_TAG, xml);
        startActivity(inten);
    }

    public void setShowErrorView(boolean isLoadError) {
        if (isLoadError) {
            llItemWebError.setVisibility(VISIBLE);
            mWebView.setVisibility(GONE);
        } else {
            llItemWebError.setVisibility(GONE);
            mWebView.setVisibility(VISIBLE);
        }
    }
}
